#include "CParticle.h"
#include "CCamera.h"
#include "SGD Wrappers/CSGD_TextureManager.h"
#include "CGame.h"

CParticle::CParticle(float fPosX, float fPosY, float fVelX, float fVelY, float fAccelX, float fAccelY, float fStartScale, float fEndScale, 
		int nCurrentLife, int nMaxLife, DWORD* nColorArray, CEmitter* pOwner, int nImageID)
{
	m_fPosX = fPosX;
	m_fPosY = fPosY;

	m_fVelX = fVelX;
	m_fVelY = fVelY;
	m_fAccelX = fAccelX;
	m_fAccelY = fAccelY;

	m_fStartScale = m_fCurrentScale =  fStartScale;
	m_fEndScale = fEndScale;

	m_nCurrentLife = nCurrentLife;
	m_nMaxLife = nMaxLife;

	m_nColorArray = nColorArray;
	m_nColor = m_nColorArray[0];

	m_pOwner = pOwner;

	m_nImageID = nImageID;

	m_bIsActive = true;
}

CParticle::~CParticle()
{
	delete[] m_nColorArray;
}

void CParticle::Update(float fElapsedTime)
{
	m_nCurrentLife -= fElapsedTime*1000;

	if(m_nCurrentLife <= 0)
	{
		m_bIsActive = false;
	}
	else
	{
		if (m_fCurrentScale > m_fEndScale)
            m_fCurrentScale -= (m_fStartScale / (float)m_nMaxLife) * (fElapsedTime*1000);
        else
            m_fCurrentScale += (m_fEndScale / (float)m_nMaxLife) * (fElapsedTime*1000);

		int index = 100 - (int)(100*((float)m_nCurrentLife/(float)m_nMaxLife));
		if( index >= 100)
              index = 99;
		else if(index < 0 )
              index = 0;
		m_nColor = m_nColorArray[index];

		m_fVelX += (m_fAccelX *  fElapsedTime);
		m_fVelY += (m_fAccelY *  fElapsedTime);
		m_fPosX += (m_fVelX *  fElapsedTime);
		m_fPosY += (m_fVelY *  fElapsedTime);
	}
}
void CParticle::Render()
{
	CCamera* camera = CCamera::GetInstance();
	CGame::GetInstance()->GetScreenWidth();

	if(camera->GetCameraPosX() <= m_fPosX && camera->GetCameraPosY() <= m_fPosY &&
		(camera->GetCameraPosX() + CGame::GetInstance()->GetScreenWidth()) >= m_fPosX && (camera->GetCameraPosY() + CGame::GetInstance()->GetScreenHeight()) >= m_fPosY)
		CSGD_TextureManager::GetInstance()->Draw(m_nImageID, m_fPosX-camera->GetCameraPosX(),
		m_fPosY-camera->GetCameraPosY(), m_fCurrentScale, m_fCurrentScale, 0, 0.0f, 0.0f, 0.0f, m_nColor);
	else
		m_bIsActive = false;
}